/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice.Time;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DatePicker;
import ohos.agp.components.Text;
import ohos.agp.components.TimePicker;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.WindowManager;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.global.icu.util.Calendar;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * The type Time cha cal ability slice.
 *
 * @author Xcl
 * @date 2022 /1/4
 * @package com.xcl.calculator.slice.Time
 */
public class TimeChaCalAbilitySlice extends AbilitySlice implements Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "TimeChaCalAbilitySlice");
    /**
     * The constant text.
     */
    private static String text = null;
    /**
     * The constant text1.
     */
    private static String text1 = null;
    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;
    /**
     * The Sjc 1.
     */
    private Long sjc1;
    /**
     * The Day 1.
     */
    private int day1, /**
     * The Month 1.
     */
    month1, /**
     * The Year 1.
     */
    year1;
    /**
     * The Hour 1.
     */
    private int hour1, /**
     * The Min 1.
     */
    min1, /**
     * The Sec 1.
     */
    sec1;

    /**
     * 计算两个时间相差几天几小时几秒
     *
     * @param timestamp            the timestamp
     * @param simpleDateFormatType the simple date format type
     * @return date date
     */
    private static Date DataCha(String timestamp, String simpleDateFormatType) {
        SimpleDateFormat sdf = new SimpleDateFormat(simpleDateFormatType);//要转换的时间格式
        Date date = null;
        try {
            if (timestamp.length() == 13) date = sdf.parse(sdf.format(Long.parseLong(timestamp)));
            else
                date = sdf.parse(sdf.format(Long.parseLong(timestamp) * 1000));
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return date;
    }

    /**
     * 切换后台并销毁，防止手表抽风
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.terminateAbility();
    }

    /**
     * 开始
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_time0m);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_time0t);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }

            this.findComponentById(ResourceTable.Id_timebj).setTouchEventListener(this);
            DatePicker datePicker = (DatePicker) this.findComponentById(ResourceTable.Id_date_picker);
            TimePicker timePicker = (TimePicker) this.findComponentById(ResourceTable.Id_date_picker1);
            timePicker.setBindStateChangedListener(new Component.BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    component.setTouchFocusable(true);
                    component.setVibrationEffectEnabled(true);
                    component.requestFocus();
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {
                }
            });
            this.findComponentById(ResourceTable.Id_tstart_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    int day;
                    int month;
                    int year;
                    int hour;
                    int min;
                    int sec;
                    day = datePicker.getDayOfMonth();
                    month = datePicker.getMonth();
                    year = datePicker.getYear();
                    min = timePicker.getMinute();
                    hour = timePicker.getHour();
                    sec = timePicker.getSecond();
                    Calendar cal = Calendar.getInstance();
                    cal.set(Calendar.HOUR_OF_DAY, hour);
                    cal.set(Calendar.MINUTE, min);
                    cal.set(Calendar.SECOND, sec);
                    cal.set(Calendar.DAY_OF_MONTH, day);
                    cal.set(Calendar.MONTH, month);
                    cal.set(Calendar.YEAR, year);
                    Long sjc = cal.getTimeInMillis() / 1000;
                    TimeChaCalAbilitySlice.this.sjc1 = sjc;
                    TimeChaCalAbilitySlice.this.day1 = day;
                    TimeChaCalAbilitySlice.this.month1 = month;
                    TimeChaCalAbilitySlice.this.year1 = year;
                    TimeChaCalAbilitySlice.this.min1 = min;
                    TimeChaCalAbilitySlice.this.sec1 = sec;
                    TimeChaCalAbilitySlice.this.hour1 = hour;
                    Text question = (Text) TimeChaCalAbilitySlice.this.findComponentById(ResourceTable.Id_tsjc_field);
                    question.setText("开始时的时间戳为:" + sjc);
                }
            });//gg2
            DatePicker datePicker1 = (DatePicker) this.findComponentById(ResourceTable.Id_date_picker);
            TimePicker timePicker1 = (TimePicker) this.findComponentById(ResourceTable.Id_date_picker1);
            this.findComponentById(ResourceTable.Id_tend_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    Text question = (Text) TimeChaCalAbilitySlice.this.findComponentById(ResourceTable.Id_tcha_field);
                    int day;
                    int month;
                    int year;
                    int hour;
                    int min;
                    int sec;
                    try {
                        day = datePicker1.getDayOfMonth();
                        month = datePicker1.getMonth();
                        year = datePicker1.getYear();
                        min = timePicker1.getMinute();
                        hour = timePicker1.getHour();
                        sec = timePicker1.getSecond();
                        Calendar cal = Calendar.getInstance();
                        cal.set(Calendar.HOUR_OF_DAY, hour);
                        cal.set(Calendar.MINUTE, min);
                        cal.set(Calendar.SECOND, sec);
                        cal.set(Calendar.DAY_OF_MONTH, day);
                        cal.set(Calendar.MONTH, month);
                        cal.set(Calendar.YEAR, year);
                        Long sjc = cal.getTimeInMillis() / 1000;
                        Date now = TimeChaCalAbilitySlice.DataCha(String.valueOf(sjc), "yyyy-MM-dd HH:mm:ss");
                        Date date = TimeChaCalAbilitySlice.DataCha(String.valueOf(TimeChaCalAbilitySlice.this.sjc1), "yyyy-MM-dd HH:mm:ss");
                        long l = now.getTime() - date.getTime();
                        long day3 = l / (24 * 60 * 60 * 1000);
                        long hour3 = (l / (60 * 60 * 1000) - day3 * 24);
                        long min3 = ((l / (60 * 1000)) - day3 * 24 * 60 - hour3 * 60);
                        long s = (l / 1000 - day3 * 24 * 60 * 60 - hour3 * 60 * 60 - min3 * 60);
                        question.setText("在" + day3 + "天" + hour3 + "小时" + min3 + "分" + s + "秒之前");
                    } catch (Exception e) {
                        XLog.error(TimeChaCalAbilitySlice.label, e.getMessage());
                        question.setText("出错了!");
                    }
                }
            });//tcha_field
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 判断横竖屏V3.6.0已弃用
     *
     * @Override protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
     * super.onOrientationChanged(displayOrientation);
     * if (displayOrientation == AbilityInfo.DisplayOrientation.PORTRAIT) {//竖屏
     * getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);
     * ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
     * .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
     * int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
     * if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
     * setUIContent(ResourceTable.Layout_time0m);
     * XLog.warn(label, "tzx deviceType 手机");
     * } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
     * setUIContent(ResourceTable.Layout_time0st);
     * XLog.warn(label, "tzx deviceType 平板");
     * } else if (localDeviceType == DeviceInfo.DeviceType.WEARABLE.value()) {
     * XLog.warn(label, "tzx deviceType 手表 不支持！");
     * } else {
     * XLog.warn(label, "tzx deviceType 暂不支持您的设备: " + localDeviceInfo.getType());
     * terminateAbility();
     * }
     * } else if (displayOrientation == AbilityInfo.DisplayOrientation.LANDSCAPE) {//横屏
     * getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);
     * ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
     * .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
     * int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
     * if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
     * setUIContent(ResourceTable.Layout_time0hm);
     * XLog.warn(label, "tzx deviceType 手机");
     * } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
     * setUIContent(ResourceTable.Layout_time0ht);
     * XLog.warn(label, "tzx deviceType 平板");
     * } else if (localDeviceType == DeviceInfo.DeviceType.WEARABLE.value()) {
     * XLog.warn(label, "tzx deviceType 手表 不支持！");
     * } else {
     * XLog.warn(label, "tzx deviceType 暂不支持您的设备: " + localDeviceInfo.getType());
     * terminateAbility();
     * }
     * }
     * <p>
     * findComponentById(ResourceTable.Id_timebj).setTouchEventListener(this);
     * <p>
     * findComponentById(ResourceTable.Id_tstart_button).setClickedListener(new Component.ClickedListener() {
     * @Override public void onClick(Component v) {
     * int day, month, year, hour, min, sec;
     * DatePicker datePicker = (DatePicker) findComponentById(ResourceTable.Id_date_picker);
     * day = datePicker.getDayOfMonth();
     * month = datePicker.getMonth();
     * year = datePicker.getYear();
     * TimePicker timePicker = (TimePicker) findComponentById(ResourceTable.Id_date_picker1);
     * min = timePicker.getMinute();
     * hour = timePicker.getHour();
     * sec = timePicker.getSecond();
     * Calendar cal = Calendar.getInstance();
     * cal.set(Calendar.HOUR_OF_DAY, hour);
     * cal.set(Calendar.MINUTE, min);
     * cal.set(Calendar.SECOND, sec);
     * cal.set(Calendar.DAY_OF_MONTH, day);
     * cal.set(Calendar.MONTH, month);
     * cal.set(Calendar.YEAR, year);
     * Long sjc = cal.getTimeInMillis() / 1000;
     * sjc1 = sjc;
     * day1 = day;
     * month1 = month;
     * year1 = year;
     * min1 = min;
     * sec1 = sec;
     * hour1 = hour;
     * Text question = (Text) findComponentById(ResourceTable.Id_tsjc_field);
     * question.setText("开始时的时间戳为:" + sjc);
     * }
     * });//gg2
     * findComponentById(ResourceTable.Id_tend_button).setClickedListener(new Component.ClickedListener() {
     * @Override public void onClick(Component v) {
     * Text question = (Text) findComponentById(ResourceTable.Id_tcha_field);
     * int day, month, year, hour, min, sec;
     * try {
     * DatePicker datePicker1 = (DatePicker) findComponentById(ResourceTable.Id_date_picker);
     * day = datePicker1.getDayOfMonth();
     * month = datePicker1.getMonth();
     * year = datePicker1.getYear();
     * TimePicker timePicker1 = (TimePicker) findComponentById(ResourceTable.Id_date_picker1);
     * min = timePicker1.getMinute();
     * hour = timePicker1.getHour();
     * sec = timePicker1.getSecond();
     * Calendar cal = Calendar.getInstance();
     * cal.set(Calendar.HOUR_OF_DAY, hour);
     * cal.set(Calendar.MINUTE, min);
     * cal.set(Calendar.SECOND, sec);
     * cal.set(Calendar.DAY_OF_MONTH, day);
     * cal.set(Calendar.MONTH, month);
     * cal.set(Calendar.YEAR, year);
     * Long sjc = cal.getTimeInMillis() / 1000;
     * Date now = DataCha(String.valueOf(sjc), "yyyy-MM-dd HH:mm:ss");
     * Date date = DataCha(String.valueOf(sjc1), "yyyy-MM-dd HH:mm:ss");
     * long l = now.getTime() - date.getTime();
     * long day3 = l / (24 * 60 * 60 * 1000);
     * long hour3 = (l / (60 * 60 * 1000) - day3 * 24);
     * long min3 = ((l / (60 * 1000)) - day3 * 24 * 60 - hour3 * 60);
     * long s = (l / 1000 - day3 * 24 * 60 * 60 - hour3 * 60 * 60 - min3 * 60);
     * question.setText("在" + day3 + "天" + hour3 + "小时" + min3 + "分" + s + "秒之前");
     * } catch (Exception e) {
     * question.setText("出错了!");
     * }
     * }
     * });//tcha_field
     * }
     */

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            ohos.global.resource.ResourceManager resManager = this.getResourceManager();
            try {
                text = resManager.getElement(ResourceTable.String_titles).getString();
                text1 = resManager.getElement(ResourceTable.String_titlex).getString();
            } catch (Exception e) {
                XLog.error(label, e.getMessage());
            }
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 43 && Math.abs(this.starx - this.endx) > 163) {
                    //Intent intent = new Intent();
                    //present(new TimeCalAbilitySlice(), intent);
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.Time.TimeCalAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "左滑了");
                } else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 43 && Math.abs(this.starx - this.endx) > 163) {
                    //Intent intent = new Intent();
                    //present(new CaiDanAbilitySlice(), intent);
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.CaiDanAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "右滑了");
                } else if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "上滑了");
                else if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "下滑了");
                else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }

    /**
     * 展示数据
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 退出
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return boolean boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog("程序退出成功，感谢您的使用!");
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

}
